﻿using AmazonMODEL;
using MODEL;
using SysCommon.WinServices;
using SysController;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;

namespace AmazonMWS
{
    partial class ReportsServices : ServiceBase,IServiceController
    {
        public ReportsServices()
        {
            InitializeComponent();
        } 

        public void Start()
        {
            SysCommon.Log.Log.Write("Reports Services Start...");
         }

        #region 2015-11-04 申请报告  - static void RequestReport(ReportType type)
        /// <summary>
        /// 2015-11-04 申请报告
        /// </summary>
        /// <param name="type"></param>
        private static void RequestReport(ReportType type)
        { 
            string reportType = type.ToString();
            foreach (var appkey in SystemController.RunAccount)
            { 
                ReportsInfo model = new ReportsInfo()
                {
                    AccountInfoId = appkey.AccountInfoID,
                    ReportType = reportType
                };
                SysCommon.Log.Log.Write(string.Format("申请 {0} 报告", reportType));
                model = ReportsController.RequestReport(appkey, model, reportType);
                if (model == null)
                    continue;
                bool IsAgain = true;
            Again: int row = SystemController.AddReportsInfo(model);
                if (row < 1)
                {
                    //TODO:
                    if (IsAgain)
                    {
                        IsAgain = false;
                        goto Again;
                    }
                    continue;
                }
            }
        }
        #endregion

        #region 2015-11-04 报告进度 - static void GetReportProcessingStatus(ReportType type)
        /// <summary>
        /// 2015-11-04 报告进度
        /// </summary>
        /// <param name="type"></param>
        private static void GetReportProcessingStatus(ReportType type)
        {
            string reportType = type.ToString();
            foreach (var appkey in SystemController.RunAccount)
            {
                List<ReportsInfo> listReport = SystemController.GetReportsInfo(appkey.AccountInfoID, ReportProcessingStatus._SUBMITTED_).Take(50).ToList();
                if (listReport == null || listReport.Count < 1)
                    continue;
                SysCommon.Log.Log.Write(string.Format("获取报告 {0} 进度", reportType));
                listReport = ReportsController.GetReportRequestList(appkey, listReport, reportType);
                bool IsAgain = true;
            Again: int row = SystemController.ModifyReportsInfo(listReport);
                if (row < 1)
                {
                    //TODO:
                    if (IsAgain)
                    {
                        IsAgain = false;
                        goto Again;
                    }
                    continue;
                }
            }
        }
        #endregion

        #region 2015-11-04 报告下载 - void GetReport_1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        /// <summary>
        /// 2015-11-04 报告下载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void GetReport_1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            foreach (var appkey in SystemController.RunAccount)
            { 
                List<ReportsInfo> listReport = SystemController.GetReportsInfo(appkey.AccountInfoID, ReportProcessingStatus._DONE_).Take(100).ToList();
                if (listReport == null || listReport.Count < 1)
                    continue;
                SysCommon.Log.Log.Write("报告下载");
                List<ReportsInfo> list = new List<ReportsInfo>();
                foreach (var ls in listReport)
                {
                    ReportsInfo model = ReportsController.GetReport(appkey, ls);
                    model.IsDel = false;
                    model.UpdateTime = DateTime.Now;
                    model.UpdateUser = "GetReport";
                    model.ReportProcessingStatus = ReportProcessingStatus.Complete.ToString();
                    list.Add(model);
                }
                bool IsAgain = true;
            Again: int row = SystemController.ModifyReportsInfo(list);
                if (row < 1)
                {
                    if (IsAgain)
                    {
                        IsAgain = false;
                        goto Again;
                    }
                    continue;
                }
            }
        }
        #endregion

        #region 2015-11-06 解析报告 - void ReportAnalyze_2_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        /// <summary>
        /// 2015-11-06 解析报告
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ReportAnalyze_2_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            foreach (var appkey in SystemController.RunAccount)
            {
                List<ReportsInfo> listReport = SystemController.GetReportsInfo(appkey.AccountInfoID, ReportProcessingStatus.Complete);
                if (listReport.Count < 1 || listReport == null)
                    continue;
                SysCommon.Log.Log.Write("解析报告");
                SellerListing(listReport);
                SellerDetailsListing(listReport);
            }
        }
        #endregion

        /*=========================================================================*/

        #region 2015-11-06 下载在线数据(Sku,Asin,Price,Quantity) -  void GetSellerListing_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        /// <summary>
        /// 2015-11-06 下载在线数据(Sku,Asin,Price,Quantity)
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void GetSellerListing_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            RequestReport(ReportType._GET_FLAT_FILE_OPEN_LISTINGS_DATA_);
            GetReportProcessingStatus(ReportType._GET_FLAT_FILE_OPEN_LISTINGS_DATA_); 
        }
        #endregion

        #region 2015-11-06 在线数据报告解析 + static void SellerListing(List<ReportsInfo> list)
        /// <summary>
        /// 2015-11-06 在线数据报告解析
        /// </summary>
        /// <param name="AccountInfoId"></param>
        public static void SellerListing(List<ReportsInfo> list)
        {
            string type = ReportType._GET_FLAT_FILE_OPEN_LISTINGS_DATA_.ToString();
            List<ReportsInfo> listing = list.Where(s => s.ReportType == type).ToList();
            if (listing == null && listing.Count < 1)
                return;
            string outStr = null;
            List<ReportsInfo> listUpdate = new List<ReportsInfo>();
            foreach (var item in listing)
            {
                DataTable dt = SysCommon.FileHelper.ImportTxtToTable(item.ResultData, out outStr);
                if (dt.Rows.Count < 1) continue;
                List<SellerListing> sellerList = new List<SellerListing>();
                foreach (DataRow dr in dt.Rows)
                {
                    SellerListing model = new SellerListing();
                    model.AccountInfoId = item.AccountInfoId;
                    model.ASIN = dr["asin"].ToString();
                    model.SKU = dr["sku"].ToString();
                    model.Price = Convert.ToDecimal(dr["price"]);
                    model.Quantity = Convert.ToInt16(dr["quantity"]);
                    model.UpdateTime = DateTime.Now;
                    model.UpdateUser = "SellerListing";
                    model.IsDel = false;
                    model.CreateTime = DateTime.Now;
                    model.CreateUser = "SellerListing";
                    sellerList.Add(model);
                }
                item.IsDel = true;
                item.UpdateTime = DateTime.Now;
                item.UpdateUser = "SellerListing";
                listUpdate.Add(item);
                bool IsAgain = true;
            Again: int row = SystemController.AddSellerListing(sellerList);
                if (row < 1)
                {
                    if (IsAgain)
                    {
                        IsAgain = false;
                        goto Again;
                    }
                    continue;
                }
                else
                {
                    bool IsAgainReports = true;
                AgainReports: int count = SystemController.ModifyReportsInfo(listUpdate);
                    if (count < 1)
                    {
                        if (IsAgainReports)
                        {
                            IsAgainReports = false;
                            goto AgainReports;
                        }
                    }
                }
            }
        }
        #endregion

        #region 2015-11-10 下载在线详细数据 - void GetSellerDetailsListing_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        /// <summary>
        /// 2015-11-10 下载在线详细数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void GetSellerDetailsListing_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            RequestReport(ReportType._GET_MERCHANT_LISTINGS_DATA_);
            GetReportProcessingStatus(ReportType._GET_MERCHANT_LISTINGS_DATA_); 
        }
        #endregion
         
        #region 2015-11-10 在线详细数据报告解析 +  static void SellerDetailsListing(List<ReportsInfo> list)
        /// <summary>
        /// 2015-11-10 在线详细数据报告解析
        /// </summary>
        /// <param name="list"></param>
        /// <param name="account"></param>
        public static void SellerDetailsListing(List<ReportsInfo> list)
        {
            string type = ReportType._GET_MERCHANT_LISTINGS_DATA_.ToString();
            List<ReportsInfo> listDetails = list.Where(s => s.ReportType == type).ToList();
            if (listDetails == null && listDetails.Count < 1)
            {
                return;
            }
            string outStr = null;
            List<ReportsInfo> listUpdate = new List<ReportsInfo>();
            foreach (var item in listDetails)
            {
                List<SellerDetailsListing> listDetail = new List<MODEL.SellerDetailsListing>();
                DataTable dt = SysCommon.FileHelper.ImportTxtToTable(item.ResultData, out outStr);
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    DataRow dr = dt.Rows[i];
                    #region SellerDetailsListing
                    SellerDetailsListing model = new SellerDetailsListing()
                    {
                        add_delete = (dr["add-delete"] ?? "").ToString(),
                        asin1 = (dr["asin1"] ?? "").ToString(),
                        asin2 = (dr["asin2"] ?? "").ToString(),
                        asin3 = (dr["asin3"] ?? "").ToString(),
                        bid_for_featured_placement = (dr["bid-for-featured-placement"] ?? "").ToString(),
                        CreateTime = DateTime.Now,
                        CreateUser = "SellerDetailsListing",
                        expedited_shipping = (dr["expedited-shipping"] ?? "").ToString(),
                        fulfillment_channel = (dr["fulfillment-channel"] ?? "").ToString(),
                        image_url = (dr["image-url"] ?? "").ToString(),
                        IsDel = false,
                        item_condition = (dr["item-condition"] ?? "").ToString(),
                        item_description = (dr["item-description"] ?? "").ToString(),
                        item_is_marketplace = (dr["item-is-marketplace"] ?? "").ToString(),
                        item_name = (dr["item-name"] ?? "").ToString(),
                        item_note = (dr["item-note"] ?? "").ToString(),
                        listing_id = (dr["listing-id"] ?? "").ToString(),
                        open_date = (dr["open-date"] ?? "").ToString(),
                        pending_quantity = (dr["pending-quantity"] ?? "").ToString(),
                        price = Convert.ToDecimal(dr["price"] ?? 0),
                        product_id = (dr["product-id"] ?? "").ToString(),
                        product_id_type = (dr["product-id-type"] ?? "").ToString(),
                        quantity = Convert.ToInt32(dr["quantity"] ?? 0),
                        seller_sku = (dr["seller-sku"] ?? "").ToString(),
                        will_ship_internationally = (dr["will-ship-internationally"] ?? "").ToString(),
                        zshop_boldface = (dr["zshop-boldface"] ?? "").ToString(),
                        zshop_browse_path = (dr["zshop-browse-path"] ?? "").ToString(),
                        zshop_category1 = (dr["zshop-category1"] ?? "").ToString(),
                        zshop_shipping_fee = (dr["zshop-shipping-fee"] ?? "").ToString(),
                        zshop_storefront_feature = (dr["zshop-storefront-feature"] ?? "").ToString(),
                        AccountInfoId = item.AccountInfoId
                    };
                    #endregion
                    listDetail.Add(model);
                }
                bool IsAgain = true;
            Again: int row = SystemController.AddSellerDetailsListing(listDetail);
                if (row < 1)
                {
                    if (IsAgain)
                    {
                        IsAgain = false;
                        goto Again;
                    }
                    continue;
                }
                else
                {
                    item.IsDel = true;
                    item.UpdateTime = DateTime.Now;
                    item.UpdateUser = "SellerDetailsListing";

                    listUpdate.Add(item);
                }
            }
            bool IsAgainDetails = true;
        AgainDetails: int count = SystemController.ModifyReportsInfo(listUpdate);
            if (count < 1)
            {
                if (IsAgainDetails)
                {
                    IsAgainDetails = false;
                    goto AgainDetails;
                }
            }
        }
        #endregion

        public static void GetBrowesNodes()
        {
            RequestReport(ReportType._GET_XML_BROWSE_TREE_DATA_);
            GetReportProcessingStatus(ReportType._GET_XML_BROWSE_TREE_DATA_);

        }

        public static void Btg()
        {
            string path = @"C:\Users\飛龍\Desktop\AmazonData\AmazonData\browse_tree_data_AmazonFR.xml";
            using (StreamReader reader = File.OpenText(path))
            {
                string str = reader.ReadToEnd();
                Result result = SysCommon.XmlHelper.XmlDeserialize<Result>(str, Encoding.UTF8);


                List<AmazonBrowseNode> listNodes = new List<AmazonBrowseNode>();
                List<AmazonRefinementsInfo> listRefinement = new List<AmazonRefinementsInfo>();
                foreach (ResultNode item in result.Node)
                {
                    AmazonBrowseNode node = new AmazonBrowseNode()
                    {
                        BrowseNodeId = item.browseNodeId,
                        BrowseNodeName = item.browseNodeName,
                        BrowseNodeStoreContextName = item.browseNodeStoreContextName,
                        BrowsePathById = item.browsePathById,
                        BrowsePathByName = item.browsePathByName,
                        ChildNodes = item.browsePathByName,
                        ChildrenCount =Convert.ToInt32( item.childNodes.count),
                        CreateTime = DateTime.Now,
                        CreateUser = "PU",
                        HasChildren = item.hasChildren ,
                         SiteId=4,
                        IsDel = false,
                        ProductTypeDefinitions = item.productTypeDefinitions,
                        RefinementsInfoCount = Convert.ToInt32(item.refinementsInformation.count)
                    };
                    listNodes.Add(node);
                    if (item.refinementsInformation.refinementName==null||item.refinementsInformation.count=="0")
                    {
                        continue;
                    }
                    foreach (var it in item.refinementsInformation.refinementName)
                    { 
                        AmazonRefinementsInfo model = new AmazonRefinementsInfo()
                        {
                            AcceptedValues = it.refinementField.acceptedValues,
                            CreateTime = DateTime.Now,
                            CreateUser = "Pu",
                            HasModifier = it.refinementField.hasModifier,
                            IsDel = false,
                            Modifiers = it.refinementField.modifiers,
                            RefinementAttribute = it.refinementField.refinementAttribute,
                            RefinementName = it.name,
                            SiteId = 4,
                            UpdateTime = DateTime.Now,
                            UpdateUser = "FL",
                            BrowseNodeId = item.browseNodeId
                        };
                        listRefinement.Add(model);
                    }
                }
                int row = SystemController.AddAmazonBrowseNode(listNodes);
                int count = SystemController.AddAmazonRefinementsInfo(listRefinement);

            }
        } 
    }
}
